# blib/log.py
#
# 

""" provide logging infrastructure. """

## blib imports

from blib import colors

## basic imports

import logging
import os
import re

## runtime logging variables

logfilter = ["looponce", "PING", "PONG"]
logplugs = []

## defines

datefmt = colors.BOLD + colors.BLUE + '%H:%M:%S' + colors.ENDC
format = "%(asctime)-8s -=- %(message)-84s -=- (%(module)s.%(lineno)s)" 
format_small = "%(asctime)-8s -=- %(message)-84s"

LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'warn': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL
        }

## Formatter class

class Formatter(logging.Formatter):

    """ hooks into the logging system. """

    def format(self, record):
        target = str(record.msg)
        if not target: target = " "
        if target[0] in [">", ]: target = "%s%s%s%s" % (colors.RED, target[0], colors.ENDC, target[1:])
        elif target[0] in ["<", ]: target = "%s%s%s%s" % (colors.GREEN, target[0], colors.ENDC, target[1:])
        else: target = "%s%s%s %s" % (colors.GREEN, "!", colors.ENDC, target)
        record.msg = "%s" % target
        return logging.Formatter.format(self, record)

## MyFilter class

class Filter(logging.Filter):

    def filter(self, record):
        for f in logfilter:
            if f in record.msg: return False
        for modname in logplugs:
            if modname in record.module: record.levelno = logging.WARN ; return True
        return True

## provide a factory function returning a logger ready for use

def log_config(loglevel):
    """ return a properly configured logger. """
    logger = logging.getLogger("")
    formatter = Formatter(format, datefmt=datefmt)
    formatter_short = Formatter(format_small, datefmt=datefmt)
    level = LEVELS.get(str(loglevel).lower(), logging.NOTSET)
    filehandler = None
    logger.setLevel(level)
    if logger.handlers:
        for handler in logger.handlers: logger.removeHandler(handler)
    try: filehandler = logging.handlers.TimedRotatingFileHandler(j(homedir, "ologs", "blib.log"), 'midnight')
    except: pass
    ch = logging.StreamHandler()
    ch.setLevel(level)
    if level < logging.WARNING: ch.setFormatter(formatter)
    else: ch.setFormatter(formatter_short)
    ch.addFilter(Filter())
    logger.addHandler(ch)
    if filehandler:
        filehandler.setLevel(level)
        logger.addHandler(filehandler)
    return logger
